<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <title>实时翻译</title>
    <link rel="stylesheet" href="../css/mui.min.css">
    <script src="../js/mui.min.js"></script>
    <!--App自定义的css-->
    <link rel="stylesheet" type="text/css" href="../css/app.css" />
    <link rel="stylesheet" href="../npl/css/vant.mini.css" />
    <script src="../js/vconsole.min.js"></script>
    <script src="../js/jquery-3.6.0.min.js"></script>
    <script src="../js/vue.js"></script>
    <script src="../js/flexible.js"></script>
    <script src="../wx/uap.js"></script>
    <script src="./text.js" type="text/javascript"></script>
    <script src="../npl/js/vant.mini.js"></script>
    <script src="../js/sm3.js"></script>
    <script src="../js/sm2.js"></script>
    <script src="./index2.js"></script>
</head>
<style>
    body {
        margin: 0;
        padding: 0;
    }

    #app {
        background-color: #fff;
    }

    .box {
        width: 100%;
        height: 100%;
        overflow: hidden;
        display: flex;
        flex-direction: column;
    }

    .form-box {
        display: flex;
        padding: 10px 10px 8px;
    }

    .van-cell--required::before {
        left: .26rem;
    }

    .form-box .van-cell {
        border-radius: 7px;
        align-items: center;
        padding: 0 .4rem;

    }

    .van-cell {
        font-weight: 500;
        font-size: 15px !important;

    }

    .form-box .van-cell.van-field--min-height {
        /* padding: 10px 10px 0; */
    }

    .van-cell__value,
    .van-field__body {
        width: 100%;
        height: 100%;
    }

    .form-box .van-field--disabled {

        color: #646566;
    }

    .form-box input[type=text] {
        border: none;
        margin-bottom: 0;
        padding: 0;
    }

    .van-nav-bar {
        /* background: none !important;; */
    }

    .wrapper {
        display: flex;
        flex-direction: column;
        flex: 1;
    }

    .van-field__control:disabled {
        width: 100%;
        height: 100%;
        -webkit-text-fill-color: #323233;
        color: #323233;
    }

    .text_b {
        display: flex;
        height: 1rem;
        width: 100%;
        background-color: #fff;
        padding: 0 20px;
        align-items: center;
        justify-content: space-between;
    }

    .text_b_imgbox {
        /* width: ; */
        display: flex;
    }

    .text_b_imgbox p {
        width: .8rem;
        height: .8rem;
    }

    .text_b_imgbox p:nth-child(1) {
        margin-right: 15px;
    }

    .text_b_imgbox p img {
        width: 100%;
        height: 100%;
    }

    .van-button--primary {
        width: 82px;
        height: .7rem !important;
        background-color: #62cccc !important;
        border: none !important;
    }

    .ldBtn {
        /* padding: 0 20px; */
    }

    .ldBtn_img {
        width: 100%;
        height: 1rem;
    }

    .ldBtn_img img {
        width: 100%;
        height: 100%;
    }

    .popTitle {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 1rem;
        padding: .6rem 0 0;
        color: #000;
        font-size: 19px;
        margin-bottom: .7rem;
        font-weight: bold;

    }

    .vanPop {
        padding: 0 10px 10px
    }

    .van-radio__icon--checked .van-icon {
        background-color: #fff !important;
        border-color: #fff !important;
        color: #19a97b !important;
    }

    .van-cell--clickable:active {
        background-color: #fff !important;
    }

    .van-icon-success:before {
        background-color: #fff !important;
        border-color: #fff !important;
    }

    .van-radio__icon .van-icon {
        border: none !important;
    }

    .van-nav-bar .van-icon {
        color: #000;
        font-size: 12px;
    }

    .jiantou {
        font-size: 25px;
    }

    .box_from {
        flex: 1;
        background-color: #F3F6FF;
        display: flex;
        flex-direction: column;
    }

    .musicPlay {
        display: flex;
        width: 100%;
        height: 58px;
    }

    .playControl {
        display: flex;
        align-items: center;
        user-select: none;
        width: 100%;
        height: 100%;
        /* margin-top: 12px; */
        justify-content: space-between;
        /* padding-top: 5px; */
        padding-left: 5px;
        /* width: 320px;
            height: 40px; */
    }

    .audioVolSpan {
        margin-right: 10px;
        margin-left: 32%;
    }

    .audioSpan,
    .audioVolSpan {
        color: #333;
        font-size: 24px;
        /* margin-right: 30px; */
        cursor: pointer;
    }

    .foot {
        /* position: fixed; */
        bottom: 0px;
        left: 0px;
        box-sizing: border-box;
        width: 100%;
        padding: 20px;
        /* height: 1.7rem; */
        text-align: center;
        display: flex;
        /* flex-direction: column; */
        justify-content: space-between;
    }

    .box_wrapper {
        width: 48%;
        position: relative;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }

    .shorthand {
        width: 100%;
        box-sizing: border-box;
        position: absolute;
        z-index: 999999;
        left: 0;
        height: .96rem;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 20px;
    }

    .hr {
        background-color: #fff;
        width: 1.5px;
        height: 0.04rem;
        float: right;
        margin-left: 6px;
        animation: liner 1s ease-in-out;
        animation-iteration-count: infinite;
        animation-direction: alternate;
    }

    .hr1,
    .hr4,
    .hr7,
    .hr10,
    .hr13,
    .hr16,
    .hr19,
    .hr22,
    .hr25 {
        animation-delay: -2s;
    }

    .hr2,
    .hr5,
    .hr8,
    .hr11,
    .hr14,
    .hr17,
    .hr20,
    .hr23,
    .hr26 {
        animation-delay: -1s;
    }

    .hr3,
    .hr6,
    .hr9,
    .hr12,
    .hr15,
    .hr18,
    .hr21,
    .hr24 {
        animation-delay: -1.5s;
    }

    @keyframes liner {
        0% {
            transform: scaleY(1);
        }

        100% {
            transform: scaleY(6);
        }
    }

    .handle_btn_tips {
        color: #707394;
        font-size: 12px;
        margin-bottom: 15px;
        line-height: 0;
    }

    .handle_btn {
        background: rgb(232, 237, 255);
        height: .96rem;
        border-radius: 30px;
    }

    .isStartTalk {
        background: url(../image/shuoyishuo_btn_bg_1.png) no-repeat;
        background-size: 100% 100%;
    }

    .handle_btn_tips span {
        font-size: 30px;
        position: relative;
        top: 4px;
    }

    .jiantou img {
        width: 15px;
    }
</style>
</head>

<body>

    <div class="box" id="app">
        <div class="is-loading">
            <div class="curtain">
                <div class="loadingBgc">
                    <div class="loader"></div>
                </div>
            </div>
        </div>
        <div class="header_tit">
            <van-nav-bar left-arrow>
                <template #left>
                    <div class="back_l" @click="home"><img src="../image/left.png" alt=""></div>
                </template>
                <template #title>
                    <div @click="popShow=true" style="display:inline;" v-html="langAct">
                    </div>
                    <!-- <div style="display:inline;">
                        <van-icon name="arrow-down" />
                    </div> -->
                </template>
                <template #right>
                    <div class="ldBtn">
                        <div class="Btn">
                            <div class="musicPlay">
                                <audio ref="audio" id="course-aud" @play="playFunc" @pause="pauseFunc" preload="auto"
                                    :src="audioSrc">
                                </audio>
                                <div class="audioControl">
                                    <div class="playControl">
                                        <span class="audioSpan" @click="clickFunc('play')"
                                            v-show="!isPlaying && isPlayings"
                                            style="margin: 0 .3rem;width: .5rem;height: .5rem;">
                                            <img style="width: 100%; height: 100%; " src="../image/stopBtn.png" alt="">
                                        </span>
                                        <span @click="clickFunc('pause',1)" class="audioSpan" v-show="isPlaying" style="
                                          margin: 0 .3rem;width: .5rem;height: .5rem;">
                                            <img style="width: 100%; height: 100%;" src="../image/starBtn.png" alt="">
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </template>
            </van-nav-bar>
        </div>
        <div class="wrapper">
            <div class="form-box">
                <van-field readonly @touchstart.prevent v-model="content" type="textarea" rows="10" ref="field1"
                    @click="demo1" id="clipboardContent" placeholder="请进行语音输入..." />

            </div>
            <div class="box_from">
                <div class="form-box" style="flex:1">
                    <van-field readonly @touchstart.prevent id='output_box_web' ref="field1" style="background:none;"
                        v-model="content1" type="textarea" style="width:100%;height:100%" disabled show-word-limit />
                </div>
                <div v-cloak class='foot' id="foot">
                    <div class="box_wrapper">
                        <div v-if="isStartTalk" class="handle_btn_tips"><span>·</span> 松开停止转写文字</div>
                        <div v-if="isStartTalk" class='shorthand'>
                            <ul>
                                <li class='uldis'>
                                    <div class="liner-box">
                                        <span class="lines">
                                            <!-- 使用 v-for 动态生成 hr 标签 -->
                                            <hr v-for="index in lineCount" :key="index" :class="`hr hr${index}`">
                                        </span>
                                    </div>
                                </li>
                            </ul>
                        </div>
                        <div v-if="!isStartTalk"></div>
                        <button class="handle_btn" :class="isStartTalk?'isStartTalk':''"
                            @mousedown="handleMouseDown('cnen')" @mouseup="handleMouseUp"
                            @touchstart="handleMouseDown('cnen')" @touchend="handleMouseUp">
                            {{isStartTalk?'':'按住说中文'}}
                        </button>
                    </div>
                    <div class="box_wrapper">
                        <div v-if="isStartTalk1" class="handle_btn_tips"><span>·</span> 松开停止转写文字</div>
                        <div v-if="isStartTalk1" class='shorthand'>
                            <ul>
                                <li class='uldis'>
                                    <div class="liner-box">
                                        <span class="lines">
                                            <!-- 使用 v-for 动态生成 hr 标签 -->
                                            <hr v-for="index in lineCount" :key="index" :class="`hr hr${index}`">
                                        </span>
                                    </div>
                                </li>
                            </ul>
                        </div>
                        <div v-if="!isStartTalk1"></div>
                        <button class="handle_btn" :class="isStartTalk1?'isStartTalk':''"
                            @mousedown="handleMouseDown('encn')" @mouseup="handleMouseUp"
                            @touchstart="handleMouseDown('encn')" @touchend="handleMouseUp">
                            {{isStartTalk1 ?'':'按住说英文'}}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </div>
</body>
<script>
    new Vue({
        el: '#app',
        data() {
            let voicelist = [];
            return {
                lineCount: 10, // 可以根据需要动态调整线条数量
                content: '',
                content1: "",
                time1: 0,
                isPlayings: false,
                ldBtn: true,
                MODEL_CODE: '1888',
                CAPACITY_CODE: '010115',
                LANG: 'zh',
                WS_URL: '',
                isStartTalk: false,
                isStartTalk1: false,
                VoiceItemID: "",
                timetimer1: null,
                count: "",
                isFlagStartTrue: false,
                popShow: false,
                myWebsocket: null,
                isPlaying: true,
                type: "cnen",
                translateWS_URL: "",
                audioSrc: "",
                textIndex: 0,
                contentText: "",
                voiceTxt: {
                    old: '',
                    ind: null
                },
                inputDom: null,
                // audioSrc: "https://baikevideo.cdn.bcebos.com/media/mda-O9xINmeZEwxyMv5u/c869e54cdfc5dd6663a0f52f16999531.mp4",
                langAct: '中 <span class="jiantou"><img src="../image/jurassic.png" alt=""></span> 英',
            }
        },
        watch: {

        },
        created() {
            $.getScript("../js/jweixin-sgccigw-1.0.0.js" /*"js/jweixin-1.0.0.js"*/ , function () {
                let jsApiList = [];
                const _this = this
                wx.ready(function () {
                    wx.onHistoryBack(() => {
                        _this.home()
                        if (_this.VoiceItemID) {
                            _this.stopRecorder()
                        }
                        return false
                    })
                });
                jsApiList = [
                    'startRecord',
                    'stopRecord',
                    'onVoiceRecordEnd',
                    'translateVoice',
                    'startRecordVoiceBuffer',
                    'ext_AudioRecorder_Start',
                    'ext_AudioRecorder_Stop',
                    'onRecordBufferReceived',
                    'multiWindows_subscribe',
                    'stopRecord',
                    "onHistoryBack"
                ];
                wx.config({
                    beta: true,
                    debug: false,
                    appId: "ww4d11a39991ebffdc",
                    timestamp: '1639582452',
                    nonceStr: "AMQGnmTMzhJetshY",
                    signature: 'fb9f560a9b4824f7db3525926994010de74ea055',
                    jsApiList: jsApiList
                });
            });
        },
        mounted() {
            this.typeWriter()
            this.inputDom = document.getElementById("clipboardContent")
            this.inputDomweb = document.getElementById("output_box_web")
            // this.testMsg()

            // window.addEventListener('resize',this.pageResize())
        },
        methods: {
            //     pageResize(){
            //   this.$nextTick(()=>{
            //     var originalHeight=document.documentElement.clientHeight
            //       window.onresize = () => {
            //           var resizeHeight=document.documentElement.clientHeight || document.body.clientHeight;
            //           if(resizeHeight<originalHeight){
            //             this.isShowTalkBtn = false
            //           } else {
            //             this.isShowTalkBtn = true
            //           }
            //       }
            //   })
            // },

            handleMouseDown(type) {
                this.timer = setTimeout(() => {
                    this.type = type
                    this.content = ""
                    this.textIndex = 0
                    this.contentText = ""
                    this.content1 = ""
                    this.timer = null;
                    this.getMeToken()
                    if (type == "cnen") {
                        this.isStartTalk = true
                    } else {
                        this.isStartTalk1 = true
                    }

                }, 500); // 触发长按事件
            },

            handleMouseUp() {
                this.isStartTalk = false
                this.isStartTalk1 = false
                clearTimeout(this.timer);
                if (this.VoiceItemID) {
                    this.VoiceItemID = ""
                    this.stopRecorder()
                    this.WS_URL = ""
                    this.myWebsocket = null,
                        this.translateWS_URL = ""
                    // this.synthesis()
                    // this.timer = null;
                    this.audioSrc = ''
                    this.isPlaying = true
                    setTimeout(() => {
                        this.translateBtn()
                    })
                }
            },
            translateBtn() {
                if (!this.content) {
                    mui.toast("无翻译的内容", {
                        duration: "long",
                        type: "div",
                    });
                    return
                }
                let userId = sessionStorage.getItem("userId");
                let Authentication = sessionStorage.getItem("Authentication");
                const timestamp = new Date().getTime() + "";
                let iscp_port;
                if (sessionStorage.getItem("iscp_port")) {
                    iscp_port = sessionStorage.getItem("iscp_port");
                } else {
                    iscp_port = "";
                }
                let data = {
                    type: this.type,
                    data: this.content,
                    timestamp: timestamp,
                };
                data = JSON.stringify(data)
                let sign = sm3(data);
                $.ajax({
                    url: localUrlLink +
                        iscp_port +
                        "/tjAiAssistant/translate/translate",
                    type: "post",
                    // async: false, //是否同步，false表示同步请求
                    dataType: "json",
                    data: data,
                    headers: {
                        "Content-Type": "application/json;charset=UTF-8",
                        sign: sign,
                        timestamp: timestamp,
                        userId: userId,
                        Authentication: Authentication,
                    },
                    success: (res, txt, xhr) => {
                        if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                            let Authentication = xhr.getResponseHeader(
                                "Authentication");
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                            if (res.code == 200) {
                                console.log(res, "内容")
                                this.contentText = res.resultValue
                                this.synthesis(1)
                            } else {

                            }

                        } else {
                            mui.toast("完整性校验失败", {
                                duration: "long",
                                type: "div",
                            });
                        }
                        //
                    },
                    error: (e) => {
                        mui.toast("请求异常，请稍后再试！", {
                            duration: "long",
                            type: "div",
                        });
                    },
                });
            },
            synthesis(num) {
                let userId = sessionStorage.getItem("userId");
                let Authentication = sessionStorage.getItem("Authentication");
                const timestamp = new Date().getTime() + "";
                let iscp_port;
                if (sessionStorage.getItem("iscp_port")) {
                    iscp_port = sessionStorage.getItem("iscp_port");
                } else {
                    iscp_port = "";
                }
                let data = {
                    text: this.contentText,
                    nativeVoiceName: localStorage.getItem("nativeVoiceName") ? localStorage.getItem(
                        "nativeVoiceName") : "panting",
                    timestamp: timestamp,
                };
                data = JSON.stringify(data)
                let sign = sm3(data);
                $.ajax({
                    url: localUrlLink +
                        iscp_port +
                        "/tjAiAssistant/voice/synthesis",
                    type: "post",
                    async: false, //是否同步，false表示同步请求
                    dataType: "json",
                    data: data,
                    headers: {
                        "Content-Type": "application/json;charset=UTF-8",
                        sign: sign,
                        timestamp: timestamp,
                        userId: userId,
                        Authentication: Authentication,
                    },
                    success: (res, txt, xhr) => {
                        if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                            let Authentication = xhr.getResponseHeader(
                                "Authentication");
                            if (res.code == 200) {
                                if (Authentication) {
                                    sessionStorage.setItem("Authentication", Authentication);
                                    if (res.resultValue) {
                                        let voiceSign = sm3(timestamp + "&" + res.resultValue);
                                        this.audioSrc = localUrlLink + iscp_port +
                                            `/tjAiAssistant/voice/getAudioByAttachmentId?Authentication=${Authentication}&id=${res.resultValue}&sign=${voiceSign}&timestamp=${timestamp}`
                                        console.log(this.audioSrc, 89898)
                                        setTimeout(() => {
                                            this.clickFunc("play", 2)
                                        }, 100)

                                    }
                                }
                            } else {
                                if (num == 1) return
                                mui.toast(res.resultValue, {
                                    duration: 'long',
                                    type: 'div'
                                })
                            }
                        } else {
                            if (num == 1) return
                            mui.toast("完整性校验失败", {
                                duration: "long",
                                type: "div",
                            });
                        }
                        //
                    },
                    error: (e) => {
                        if (num == 1) return
                        mui.toast("请求异常，请稍后再试！", {
                            duration: "long",
                            type: "div",
                        });
                    },
                });

            },
            playFunc() {
                this.playPause();
                this.isPlaying = true
                this.$emit('play', this.isPlaying)
            },
            playPause() {
                if (!this.isPlaying) {
                    this.$refs.audio.pause();
                } else {
                    this.$refs.audio.play();
                }
            },
            typeWriter() {
                const delayTimes = {
                    cnen: 48,
                    default: 200
                };

                if (this.textIndex < this.contentText.length) {
                    this.content1 += this.contentText.charAt(this.textIndex);
                    this.textIndex++;
                    const delay = delayTimes[this.type] || delayTimes.default;
                    // 递归调用 typeWriter 函数
                    setTimeout(() => {
                        this.typeWriter();
                    }, delay);

                }
            },
            clickFunc(val, num) {
                // if (!this.content1) {
                //     mui.toast("无需要朗读的内容,请先进行翻译!", {
                //         duration: "long",
                //         type: "div",
                //     });
                //     return
                // }
                if (num == 2) {
                    this.typeWriter()
                }
                if (!this.audioSrc) {
                    this.synthesis()
                    mui.toast("正在获取音频...", {
                        duration: "long",
                        type: "div",
                    });
                    return
                }

                // 开始打印字
                if (val == 'play') {
                    this.isPlaying = true
                    this.$refs.audio.play()
                } else if (val == 'pause') {

                    if (num == 1) {
                        this.isPlayings = true
                        this.isPlaying = false
                    }

                    this.$refs.audio.pause()
                }
            },
            // 暂时
            pauseFunc(e) {
                // this.isPlaying = false
                this.$emit('pause', this.isPlaying)
            },
            home() {
                $(location).attr("href", "translationPage.html");
            },
            starPlay() {
                this.ldBtn = !this.ldBtn
            },
            stopPlay() {
                this.ldBtn = !this.ldBtn
            },
            demo1() {
                // 判断光标是点击的0位还是默认直接说话
                this.$refs.field1.focus();
                var $input1 = document.getElementById("clipboardContent");
                if ($input1.selectionStart == 0) {
                    this.isFlagStartTrue = true
                }
                // this.start()
            },
            getMeToken() {
                let _that = this
                _that.VoiceItemID = generateUUID()
                // _that.countFlage = true,
                // _that.countDownFun()
                _that.voiceTxt.ind = null
                var iscp_port = ''
                if (sessionStorage.getItem("iscp_port")) {
                    iscp_port = sessionStorage.getItem("iscp_port");
                }
                userId = sessionStorage.getItem("userId");
                let AuthenticationSession = sessionStorage.getItem("Authentication");
                const timestamp = new Date().getTime() + ""
                let data = {
                    "userId": userId,
                    "timestamp": timestamp,
                }
                const datas = JSON.stringify(data)
                let sign = sm3(datas);
                $.ajax({
                    url: localUrlLink + iscp_port + "/tjAiAssistant/soundRecording/thirdparty",
                    type: "post",
                    async: false, //是否同步，false表示同步请求
                    dataType: "json",
                    data: datas,
                    headers: {
                        "Content-Type": "application/json;charset=UTF-8",
                        sign: sign,
                        Authentication: AuthenticationSession,
                    },
                    success: (res, txt, xhr) => {
                        if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                            let Authentication = xhr.getResponseHeader("Authentication")
                            if (res.code == 200) {
                                if (Authentication) {
                                    sessionStorage.setItem("Authentication", Authentication);
                                    // _that.backNum = true
                                    _that.WS_URL =
                                        `ws://127.0.0.1:${iscp_port}/websocket/asr/i?token=${res.resultValue}&capacityCode=${_that.CAPACITY_CODE}&language=${_that.LANG}&code=${_that.MODEL_CODE}&sessionId=${_that.VoiceItemID}`
                                    if (!('WebSocket' in window)) {
                                        return
                                    }
                                    // if (_that.count < 1) {
                                    wx.invoke("multiWindows_subscribe", {
                                        channelId: _that.VoiceItemID
                                    }, function (res) {
                                        console.log(res, "消息")
                                        console.log(res.data.message, "信息")
                                        if (res.data.method == "onMessage String" && res
                                            .data.channelId == _that.VoiceItemID) {
                                            _that.onMessage(res)
                                        } else if (res.data.method ==
                                            'onReconnectFinishAndDisconn') {
                                            //重连失败处理
                                        }
                                    });
                                    //     let Sign = sm3(timestamp + "&" + _that.type);

                                    //     _that.translateWS_URL =
                                    //         `ws://127.0.0.1:${iscp_port}/tjAiAssistant/websocket?Authentication=${Authentication}&timestamp=${timestamp}&type=${_that.type}&sign=${Sign}`
                                    //     console.log(_that.translateWS_URL, "后端wensocke")
                                    //     _that.myWebsocket = new WebSocket(_that.translateWS_URL);
                                    //     // 连接发生错误的回调方法
                                    //     _that.myWebsocket.onerror = (error) => {
                                    //         console.log("error", error)
                                    //         _that.onError(error);
                                    //     };
                                    //     //连接成功建立的回调方法
                                    //     _that.myWebsocket.onopen = (event) => {
                                    //         console.log("跟后端的wensocket建立成功")
                                    //     };

                                    //     _that.myWebsocket.onmessage = (evt) => {
                                    //         _that.onMessageT(evt);
                                    //     };
                                    //     //连接关闭的回调方法
                                    //     _that.myWebsocket.onclose = (evt) => {
                                    //         console.log("evt", evt)
                                    //     };
                                    // // }
                                    //1.开始录音
                                    wx.invoke("ext_AudioRecorder_Start", {
                                            data: {
                                                channelId: _that.VoiceItemID,
                                                socketUrl: _that.WS_URL
                                            }
                                        },
                                        function (res) {
                                            if (res.err_msg === 'ext_AudioRecorder_Start:ok') {}

                                            if (res.err_msg ===
                                                'ext_AudioRecorder_Start:fail') {
                                                //失败处理
                                            }
                                            if (res.err_msg ===
                                                'ext_AudioRecorder_Start:cancel') {
                                                //取消处理
                                            }
                                            if (res.err_msg ===
                                                'ext_AudioRecorder_Start:not_support ') {}
                                        })
                                }
                            } else {
                                mui.toast(res.resultValue, {
                                    duration: 'long',
                                    type: 'div'
                                })
                            }
                        }
                    },
                    error: (e) => {

                        mui.toast('请求异常,请稍后再试', {
                            duration: 1000,
                            type: 'div'
                        })
                    },
                })
            },
            onError(evt) {
                throw new Error('websocket连接失败' + evt.data);
            },
            doSend(message) {
                this.myWebsocket.readyState === 1 && this.myWebsocket.send(message);
            },
            onMessageT(evt) {
                console.log(evt.data, 7777)
                try {
                    const data = JSON.parse(evt.data);
                    this.content1 += data.payload.result[0]
                    var allowWeb = false
                    if (this.inputDomweb.clientHeight * 4 / 3 + this.inputDomweb.scrollTop > this
                        .inputDomweb
                        .scrollHeight) {
                        allowWeb = true
                    }
                    if (allowWeb) {
                        setTimeout(() => {
                            this.inputDomweb.scrollTop = this.inputDomweb.scrollHeight
                        })
                    }

                } catch (error) {
                    throw new Error('解析错误!' + error);
                }
            },
            onMessage(evt) {
                try {
                    // const data = JSON.parse(evt.data);
                    const data = JSON.parse(evt.data.message);
                    // console.log(evt.data,"内容")
                    if (data.code == 200) {
                        if (this.voiceTxt.ind == null) {
                            this.voiceTxt.ind = this.content.length
                            // this.voiceTxt.ind = this.inputDom.selectionStart
                            this.voiceTxt.old = ''
                        }
                        var allow = false
                        if (this.inputDom.clientHeight * 4 / 3 + this.inputDom.scrollTop > this.inputDom
                            .scrollHeight) {
                            allow = true
                        }
                        // 这一行是赋值的
                        data.word = data.word.replace(/[|]/g, '')
                        // data.word = data.word.replace(/[|]/g, '\n')
                        // data.word = data.word.replace(/[\n]/g, '\n\n')
                        this.insertContent(data.word)
                        if (allow) {
                            setTimeout(() => {
                                this.inputDom.scrollTop = this.inputDom.scrollHeight
                            })
                        }
                        if (data.completed == true) {
                            // this.doSend(data.word);
                            this.voiceTxt.ind += data.word.length
                            this.voiceTxt.old = ''
                            this.inputDom.setSelectionRange(this.voiceTxt.ind, this.voiceTxt.ind)
                            setTimeout(() => {
                                this.inputDom.setSelectionRange(this.voiceTxt.ind, this.voiceTxt
                                    .ind)
                            });
                        }
                    } else if (data.code == 'E000004') {
                        mui.toast("当前已达到最大并发量限制,请稍后再试", {
                            duration: 'long',
                            type: 'div'
                        })
                        this.stopRecorder()
                    } else {
                        mui.toast(data.code + "语音服务异常", {
                            duration: 'long',
                            type: 'div'
                        })
                        this.stopRecorder()
                    }
                } catch (error) {
                    throw new Error('解析错误!' + error);
                }
            },
            insertContent(txt) {
                const content = this.content
                const startIndex = this.voiceTxt.ind
                const delLength = this.voiceTxt.old.length
                this.content = this.insertTxt(content, startIndex, txt, delLength)
                this.voiceTxt.old = txt
                this.$nextTick(() => {
                    this.inputDom.setSelectionRange(this.voiceTxt.ind + txt.length, this.voiceTxt
                        .ind + txt.length)
                })
            },
            insertTxt(content, index, txt, del) {
                let arr = content.split('')
                arr.splice(index, del, txt)
                return arr.join('')
            },
          
            stopRecorder() {
                // this.myWebsocket.close()
                // let _this = this
                wx.invoke("ext_AudioRecorder_Stop", {
                        data: {}
                    },
                    function (res) {
                        console.log(res, 78787878)
                        if (res.err_msg === 'ext_AudioRecorder_Stop:ok') {

                            // this.myWebsocket = null
                        }
                        if (res.err_msg === 'ext_AudioRecorder_Stop:fail') {
                            //失败处理
                            console.log(res);
                        }
                        if (res.err_msg === 'ext_AudioRecorder_Stop:cancel') {
                            //取消处理
                            console.log(res);
                        }
                        if (res.err_msg === 'ext_AudioRecorder_Stop:not_support ') {}
                    })
            },


        }
    })
</script>

</html>